package com.main.usermanagement.domain.user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.main.common.base.base.BaseAssemblerFactory;
import com.main.common.base.resp.RespBody;
import com.main.common.base.resp.RespCode;
import com.main.common.entity.ListPage;
import com.main.common.interfaces.ForceMasterQuery;
import com.main.common.utils.QueryWrapper.DynamicQueryBuilder;
import com.main.organizationandplatformmanagement.interfaces.dto.OrganizationModelAtomsDTO;
import com.main.usermanagement.application.service.OrganizationModelAtomsService;
import com.main.usermanagement.application.service.UserService;
import com.main.usermanagement.domain.user.aggregate.User;
import com.main.usermanagement.domain.user.entity.UserAddress;
import com.main.usermanagement.domain.user.entity.UserInfo;
import com.main.usermanagement.domain.user.repository.UserAddressRepository;
import com.main.usermanagement.domain.user.repository.UserInfoRepository;
import com.main.usermanagement.domain.user.repository.UserRepository;
import com.main.usermanagement.interfaces.assembler.UserAssembler;
import com.main.usermanagement.interfaces.dto.UserDTO;
import com.main.usermanagement.interfaces.dto.UserListDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserRepository userRepository;
    @Resource
    private UserInfoRepository userInfoRepository;
    @Resource
    private UserAddressRepository userAddressRepository;
    @Autowired
    private BaseAssemblerFactory baseAssemblerFactory;

    @Resource
    private OrganizationModelAtomsService organizationModelAtomsService;

    public RespBody<List<UserDTO>> getPlatformList() {
        List<User> platformArr = userRepository.list();
        List<UserDTO> platformDTOArr = new UserAssembler(baseAssemblerFactory).toDTOs(platformArr);
        return RespBody.ok(platformDTOArr);
    }

    @Override
    public RespBody<List<UserDTO>> associateUserWithOrganizationAtom(String userId, String atomId) {
        OrganizationModelAtomsDTO organizationModelAtomsDTO;
        RespBody<OrganizationModelAtomsDTO> atomsDTORespBody = organizationModelAtomsService.getOrganizationAtom(atomId);
        if(atomsDTORespBody.getCode() == RespCode.OK.getCode()){
            organizationModelAtomsDTO = atomsDTORespBody.getBody();
        }else{
            return RespBody.fail("获取组织结构原子失败");
        }
        if (organizationModelAtomsDTO != null) {
            RespBody<String> typeNameRespBody = organizationModelAtomsService.getAtomTypeName(atomId);
            System.out.println("用户所属组织结构原子: " + organizationModelAtomsDTO.getName());
            System.out.println("组织结构原子类型: " + typeNameRespBody.getBody());
        } else {
            System.out.println("未找到组织结构原子");
        }
        return null;
    }

    @Override
    public RespBody<UserDTO> getUserById(Long userId) {
        UserAssembler userAssembler = new UserAssembler(baseAssemblerFactory);
        User user = userRepository.getById(userId);
        if(user==null){
            return RespBody.fail("");
        }
        UserInfo userInfo = userInfoRepository.findByUserId(userId) ;
        userInfo.setAddress(userAddressRepository.findByUserInfoId(userInfo.getId()));
        user.setUserInfo(userInfo);
        UserDTO userDTO = userAssembler.toDTO(user);
        return RespBody.ok(userDTO);
    }

    @Override
    @ForceMasterQuery
    public List<User> findByPhone(String phone) {
        return userRepository.findByPhone(phone);
    }

    @Override
    public Boolean removeUserById(Long userId) {
        Boolean removeUserResult =  userRepository.removeById(userId);
        UserInfo userInfo = userInfoRepository.findByUserId(userId) ;
        Boolean removeUserInfoResult = true;
        Boolean removeUserAddressResult = true;
        if(userInfo!=null){
            removeUserInfoResult =  userInfoRepository.removeById(userInfo.getId()) ;
            removeUserAddressResult = userAddressRepository.removeByUserInfoId(userInfo.getId()) ;
        }
       return  removeUserResult&&removeUserInfoResult&&removeUserAddressResult;
    }

    @Override
    public RespBody<UserListDTO> getList(ListPage listPage) {
        UserAssembler userAssembler = new UserAssembler(baseAssemblerFactory);
        Page<User> page = new Page<>(listPage.getPageNo(), listPage.getPageSize());
        Page<User> userList = userRepository.getList(page);
        List<UserDTO> userDTOList = new ArrayList<>();
        for(User user : userList.getRecords()){
            UserInfo userInfo = userInfoRepository.findByUserId(user.getId());
            UserAddress userAddress = userAddressRepository.findByUserInfoId(userInfo.getId());
            userInfo.setAddress(userAddress);
            user.setUserInfo(userInfo);
            UserDTO userDTO = userAssembler.toDTO(user);
            userDTOList.add(userDTO);
        }
        UserListDTO userListDTO = new UserListDTO();
        userListDTO.setUserDTOList(userDTOList);
        userListDTO.setPageSize(page.getSize());
        userListDTO.setPageNo(page.getCurrent());
        userListDTO.setPageCount((long) page.getRecords().size());
        userListDTO.setTotalPages(page.getPages());
        userListDTO.setTotalCount(page.getTotal());
        return RespBody.ok(userListDTO);
    }

    @Override
    public RespBody<List<User>> complexQuery(Map<String, Object> conditions) {
        QueryWrapper<User> wrapper = DynamicQueryBuilder.buildQueryWrapper(conditions);
        return RespBody.ok(userRepository.list(wrapper));
    }

}
